package com.shine.chemicalWholeProcessSystem.http;

import android.text.TextUtils;

import com.shine.chemicalWholeProcessSystem.bus.RxBus;
import com.shine.chemicalWholeProcessSystem.bus.event.LogoutEvent;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Copyright (C), 2015-2018
 * FileName: ECObserver
 * Author: Jesse
 * Date: 2018/9/6 15:27
 * Description: ${DESCRIPTION}
 * Version: 1.0
 */
public abstract class ECObserver<T> implements Observer<ECHttpResponse<T>> {

    private final static int CODE_SUCCESS = 200;

    @Override
    public void onError(Throwable e) {

        if (e instanceof ApiException) {
            _onError((ApiException) e);
        } else {

            _onError(new ApiException(e, ExceptionHandle.ERROR.UNKNOWN));
        }
    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(ECHttpResponse<T> tecHttpResponse) {
        if (tecHttpResponse.getCode() == CODE_SUCCESS) {
            _onNext(tecHttpResponse.getResult());
        } else {
            //code:301 登录失效
//            if (tecHttpResponse.getCode() == 301) {
//                RxBus.getDefault().post(new LogoutEvent());
//            }
            //若server没有返回的错误信息，则使用约定的错误提示
            if (TextUtils.isEmpty(tecHttpResponse.getMessage())) {
//                _onError(ExceptionHandle.handleException(new ApiException(new Throwable(), tecHttpResponse.getCode())));
            } else {
                _onError(new ApiException(new Throwable(tecHttpResponse.getMessage()), tecHttpResponse.getCode()));
            }
        }
    }

    @Override
    public void onComplete() {

    }

    protected abstract void _onNext(T t);

    /**
     * 错误回调
     */
    protected abstract void _onError(ApiException ex);
}
